package org.ht.controller;

import java.io.FileWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.ht.dao.BorrowmoneyDao;
import org.ht.dao.CertificationDao;
import org.ht.pojo.*;
import org.ht.service.*;
import org.ht.util.BeanUtils;
import org.ht.util.CreateRandom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class InformationController {
	@Autowired
	private InformationService informationService;
	@Autowired
	private PoundageService poundageService;
	@Autowired
	private CertificationService certificationService;
	@Autowired
	private DopeService dopeService;
	@Autowired
	private UsersService usersservice;
	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private WithdrawalService withdrawalService;

	@Autowired
	private BorrowmoneyService borrowmoneyService;

	@Autowired
	private BorrowmoneyDao borrowmoneyDao;

	@Autowired
	private BorrowcordService borrowcordService;

	@Autowired
	private CertificationDao certificationDao;

	@Autowired
	private InvestService investService;
	// 我的账户
	@RequestMapping("query")
	public String query(@RequestParam(value = "id", required = false) String id, Model model) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", id);
		Users user = informationService.query(map);
		model.addAttribute("user", user);
		Certification certification = certificationService.select(Integer.parseInt(id));

		model.addAttribute("certification", certification);
		return "personalpage";
	}

	// 账户信息查询
	@RequestMapping("find")
	public String find(@RequestParam(value = "id", required = false) String id, Model model,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", id);
		Users user = informationService.find(map);
		List<Approveitem> list = informationService.appquery();
		request.setAttribute("num", user.getUphonenumber());
		request.setAttribute("mailbox", user.getUmailbox());
		Approveitem app = list.get(0);
		model.addAttribute("list", app);
		model.addAttribute("user", user);

		return "account";
	}



	//修改还款状态ids === boid
	@RequestMapping("tohuankuanupds")
	public String tohuankuanupd(Model model, @RequestParam(value = "ids") Integer ids,
								@RequestParam(value = "id") Integer id, 
								@RequestParam(value = "money") Double money) {
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>修改还款状态");
		Borrowcord borrowcord = borrowcordService.selectByBoid(ids);
		String productId = borrowcord.getProductId();
		int bmid = Integer.parseInt(productId);
		Integer userId = borrowcord.getUserId();
		Certification c= certificationDao.select(userId);  //查询借款人账户
		
		
		/**
		 * 余额不足时
		 */
		if (c.getCbalance() - money < 0) {
			
		}
		
		c.setCbalance(c.getCbalance() - money);        //账户余额减少     
 		c.setCpaid(c.getCpaid() - money);            //欠的钱金额减少
		certificationService.update(c);
		Borrowmoney borrowmoney = borrowmoneyService.selectByUserId(userId);
		Map<String, Object> parameters = new HashMap<String, Object>();// 查询条件
		parameters.put("bid", bmid);
		List<InvestInfo> page = investService.investS(parameters);// 查出投资该项目的人
		//InvestInfo [inid=7, userid=3, brrowid=1, inmoney=12321.00, instatus=0, instyle=钱宝宝, brrowstatus=筹集中, interest=12.00%, profitmodel=等额本金, profitmoney=0.00, indate=2017-02-27 20:14:42.0, replaydate=无期限, markstatus=0]
		for (InvestInfo investInfo : page) {
			int userid = investInfo.getUserid();
			Certification certification = certificationService.select(userid);
			if (certification != null) {
				BigDecimal inmoney = investInfo.getInmoney();
				double profit = Double.parseDouble(investInfo.getInterest()) / 100.0 * inmoney.doubleValue() / Double.parseDouble(borrowmoney.getBtimelimit()) * 1.0;
//				double profit = certification.getCdue() / 12;
				//增加投资收益
				certification.setCprofit(profit + certification.getCprofit());
				//增加余额
				certification.setCbalance(certification.getCbalance() + certification.getCprofit());
				//减少待收本息
				certification.setCdue(certification.getCdue() - profit);
				certificationService.update(certification);
			}
		}

		borrowcordService.updborr(ids);


		return "redirect:repayment.do?id=" + id;
	}


	@RequestMapping("repayment")
	public String  repayment(@RequestParam(value = "id", required = false) Integer id, Model model,
					   HttpServletRequest request) {
		Borrowmoney borr = borrowmoneyService.get(id);
		model.addAttribute("borr", borr);
		model.addAttribute("list", borrowcordService.selborr(id));

		return "repayment";
	}

	@RequestMapping("repaymentList")
	public String  repaymentList(@RequestParam(value = "id", required = false) String id, Model model,
							 HttpServletRequest request) {
		HttpSession session = request.getSession();
		Users globaluser = (Users)session.getAttribute("globaluser");
		model.addAttribute("list", borrowmoneyDao.getBorrowmoney(globaluser.getUid()));
		return "repaymentList";
	}

	// 添加身份信息和认证信息
	@RequestMapping("insertUsercre")
	public String insert(@RequestParam(value = "uid", required = false) Integer uid,
			@RequestParam(value = "unickname", required = false) String unickname,
			@RequestParam(value = "aiid", required = false) Integer aiid,
			@RequestParam(value = "ainame", required = false) String ainame,
			@RequestParam(value = "realname", required = false) String realname,
			@RequestParam(value = "idnumbers", required = false) String IDnumber, Certifrecord cer) {
		System.out.println(
				"\t" + uid + "\t" + unickname + "\t" + aiid + "\t" + ainame + "\t" + realname + "\t" + IDnumber);
		Map<String, Object> map = new HashMap<>();
		map.put("uname", realname);
		map.put("ucardid", IDnumber);
		map.put("uid", uid);
		informationService.addUsers(map);   //update users u set u.uname=#{uname},u.ucardid=#{ucardid} where u.uid=#{uid}
		cer.setCruserid(uid);
		cer.setCrusername(unickname);
		cer.setCraiid(aiid);
		cer.setCrainame(ainame);
		informationService.addcertifrecord(cer);
		return "redirect:/find.do?id=" + uid;
	}

	//模拟添加第三方身份信息
	@RequestMapping("insertucertnum")
	public String insertucertnumber(@RequestParam(value="id",required=false) String id,
									@RequestParam(value="uname",required=false) String uname,
									@RequestParam(value="ucardid",required=false) String ucardid,
									@RequestParam(value="umailbox",required=false) String umailbox,
									@RequestParam(value="uphonenumber",required=false) String uphonenumber,
									@RequestParam(value="upwd_zd",required=false) String upwd_zd){
		Map<String, Object> map=new HashMap<>();
		map.put("id", id);
		int ucertnumber = (int)((Math.random()*9+1)*100000);
		String s = String.valueOf(ucertnumber);
		map.put("ucertnumber", s);
		map.put("uname", uname);
		map.put("ucardid", ucardid);
		map.put("umailbox", umailbox);
		map.put("uphonenumber", uphonenumber);
		map.put("upwd_zd", upwd_zd);
		informationService.upucertnum(map);
		/*Certification certification = new Certification();
		certification.setCrealname(uname);
		certification.setId(Integer.parseInt(id));
		certificationService.updateRealname(certification);*/
		return "redirect:/find.do?id="+id;
	}
	//获取金额，提现
	@RequestMapping("withdraw")
	public String withdraw(@RequestParam(value="id",required=false) Integer id,Model model) {
		model.addAttribute("cer", certificationService.select(id));
		return "Withdraw";
	}
	//获取金额，提现
	@RequestMapping("withdrawpay")
	@ResponseBody
	public String withdrawpay(@RequestParam(value="id",required=false) String id,
			@RequestParam(value="actualMoney",required=false) String actualMoney,
			@RequestParam(value="actualFee",required=false) String actualFee) {
		//actualMoney提现金额， actualFee 提现金额-手续费
		Users users = usersservice.selectByUid(Integer.valueOf(id));
		Certification certification = certificationService.select(Integer.parseInt(id));
		double banlance = certification.getCbalance();
		double totalMoney = certification.getCtotalmoney();
		double af = 0;     //1%的手续费
		if (Double.parseDouble(actualMoney) - Double.parseDouble(actualFee) >= 100){  
			af = Double.parseDouble(actualMoney) - 100;
		}else{
			af = Double.parseDouble(actualMoney);
		}
		
		double amf = banlance - af;      //余额 - 提现金额
		
		 /***
		  * 余额不足的情况
		  */
		if (amf < 0) {   
			return "0";
		}
		
		
		
		double bmf = totalMoney - af;	   //总金额 - 提现金额
		Map<String, Object> map = new HashMap<>();
		map.put("uid", id);
		map.put("cbalance",String.valueOf(amf));
		map.put("ctotalmoney",String.valueOf(bmf));
		certificationService.upm(map);

		Withdrawal withdrawal = new Withdrawal();
		withdrawal.setUid(users.getUid());
		withdrawal.setUname(users.getUnickname());
		withdrawal.setZname(users.getUname());
		withdrawal.setTxbank("支付宝");
		withdrawal.setStatu("2");    //待审核
		withdrawal.setTxmoney(actualMoney);
		withdrawal.setDzmoney(String.valueOf(af));
		withdrawal.setSxf(String.valueOf(Double.parseDouble(actualMoney) * 0.01));
		withdrawal.setTxtime(new Date());
		withdrawal.setShtime(Calendar.getInstance().getTime());
		withdrawalService.insertSelective(withdrawal);
		//return "redirect:/withdraw.do?id="+Integer.parseInt(id);
		return "1";
	}

	@RequestMapping("thirdparty")
	public String withdrawpay(@RequestParam(value="id",required=false) String id, HttpServletRequest request) {
		HttpSession session = request.getSession();
		Users globaluser = (Users)session.getAttribute("globaluser");
		Users user = usersservice.byNameFindUsers(globaluser.getUnickname(), globaluser.getUpassword());
		org.springframework.beans.BeanUtils.copyProperties(user, globaluser);
		session.setAttribute("globaluser", globaluser);
		return "thirdparty";
	}

	// 修改用户密码
	@RequestMapping("updpassword")
	public String updpassword(@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "updatePassForm:repassword", required = false) String password) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", id);
		map.put("password", password);
		informationService.updPassword(map);
		return "redirect:/find.do?id=" + id;
	}
	//修改手机号码
	@RequestMapping("updphone")
	public String updphone(@RequestParam(value="id",required=false)String id,
							@RequestParam(value="newPhone",required=false) String newPhone){
		System.out.println("用户id:"+id+"新手机号:"+newPhone);
		Map<String, Object> map=new HashMap<>();
		map.put("id", id);
		map.put("phone", newPhone);
		informationService.updphone(map);
		return "redirect:/find.do?id="+id;
	}

	//获取验证码
	@RequestMapping("identifying")
	@ResponseBody
	public int  identifying(){
		int i= CreateRandom.random();
		try {
		System.out.println("-------");
		System.out.println("随机数"+i);
		FileWriter fw;
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				Date date=new Date();
				fw = new FileWriter ("E://test.txt");
				fw.write ("发送时间:"+format.format(date)+"验证码:"+i);
		        fw.flush();
		        fw.close ();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return i;
	}
	//用户充值
	@RequestMapping("userpay")
	@ResponseBody
	@Transactional
	public String userpay(Poundage poundage){
		String code="200";
		Date date = new Date();
		Map<String, Object> usermap = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		usermap.put("id", poundage.getuID());
		Users user = informationService.find(usermap);
		poundage.setUname(user.getUnickname());
		poundage.setZname(user.getUname());
		poundage.setWhat("充值");
		poundage.setSxtime(date);
		poundage.setBookaccount(user.getUid()+"");
		poundage.setPaytype("快捷支付");
		Certification certification = certificationService.select(poundage.getuID());
		//可用余额
		Double cbal = certification.getCbalance();
		String xmoney = poundage.getSxmoney();
		Float fmoney = cbal.floatValue() + Float.valueOf(xmoney);
		//总余额
		Double totalMoney = certification.getCtotalmoney();
//		Float money = totalMoney.floatValue() + Float.valueOf(xmoney);
		map.put("uid", poundage.getuID());
		map.put("cbalance", fmoney.toString());
		map.put("ctotalmoney", totalMoney.toString());

		Dope dope = new Dope();
		dope.setDprimkey(poundage.getuID());
		dope.setDtitle("充值成功");
		dope.setDetails("尊敬的"+user.getUnickname()+",您通过"+poundage.getPaytype()+"充值的"+poundage.getSxmoney()+"元已到账!");
		dope.setDtime(date);


		Recharge recharge = new Recharge();
		recharge.setUid(user.getUid());
		recharge.setUname(user.getUnickname() != null ? user.getUnickname() : null);
		recharge.setZname(user.getUname() != null ? user.getUname() : null);
		recharge.setCzlx("线上充值");
		recharge.setLsh(String.valueOf(Calendar.getInstance().getTimeInMillis()));
		recharge.setCzmoney(poundage.getSxmoney());
		recharge.setDzmoney(poundage.getSxmoney());
		recharge.setCztime(new Date());
		recharge.setStatu("成功");
		//增加充值明细表数据
		poundageService.insert(poundage);
		//增加账户金额数据
		certificationService.undate(map);
		//添加广播数据
		dopeService.insert(dope);
		//添加充值记录
		rechargeService.insertSelective(recharge);
		return code;
	}
	//用户资金记录
	@RequestMapping("listpay")
	public String listpay(Model model, @RequestParam(value = "currpage", required = false) String currpage,@RequestParam(value = "id", required = false) String id) {
		int pagerow = 5;// 每页5行
		int currpages = 1;// 当前页
		int totalpage = 0;// 总页数
		int totalrow = 0;// 总行数
		Poundage poundage = new Poundage();
		List<Poundage> list = poundageService.findList(BeanUtils.toMap(poundage));
		totalrow = list.size();// 获取总行数
		if (currpage != null && !"".equals(currpage)) {
			currpages = Integer.parseInt(currpage);
		}
		totalpage = (totalrow + pagerow - 1) / pagerow;
		if (currpages < 1) {
			currpages = 1;
		}
		if (currpages > totalpage) {
			if(totalpage<1){
				totalpage=1;
			}
			currpages = totalpage;
		}
		Integer startPage = (currpages - 1) * pagerow;
		return null;
	}

	
}
